/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.metadata.schemasutilities;

import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

//import uk.ljmu.metadata.utilities.RdfFunctions;

public class RelsExtUtilities {
private static final Logger log = Logger.getLogger(RelsExtUtilities.class);
	
	//RELS_EXT file management
	/**
	 * Search for a given property in an RDF file
	 * 
	 * @param propertyName
	 * @param xmlContents
	 * @return true if the element is present, otherwise false
	 */
	@SuppressWarnings("unchecked")
	public static boolean findRELSProperty(String propertyName, String xmlContents)
	{
		//Create document
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xmlContents);
		} catch (DocumentException e) {
			log.fatal(e.getMessage());
		}
		if (doc != null)
		{
			String xPath = "//rdf:RDF/rdf:Description/*";

			List<Node> nodes = doc.selectNodes( xPath );
			for (Node node : nodes)
			{
				if (node.getName().equals(propertyName))
					return true;
			}
			return false;
		} 
		else
		{
			log.info("Error while creating XML Document");
			return false;
		}

	}
	/**
	 * Add a given property to a RELS-EXT file
	 * 
	 * @param propertyName
	 * @param propertyValue
	 * @param xmlContents
	 * @return XML string containing the updated documents, if error return the original document
	 */
	public static String addRELSProperty(String propertyName, String propertyValue, String xmlContents)
	{
		//Create document
		Document doc = null;
		String newXML = "";
		
		try 
		{
			doc = DocumentHelper.parseText(xmlContents);
		} catch (DocumentException e) {
			log.fatal(e.getMessage());
		}
		if (doc != null)
		{
			Element root = doc.getRootElement();
			Element desc = root.element("Description");
			//Check if the property already exists
			if (!SchemasProcessing.checkPropertyExistence(desc, propertyName, propertyValue))
			{
				Element property = DocumentHelper.createElement(propertyName);
				property.addAttribute("rdf:resource", propertyValue);
				desc.add(property);
				newXML = doc.asXML();

				return newXML;
			}
			return xmlContents;
		} 
		else
		{
			log.info("Error while creating XML Document");
			return xmlContents;
		}
	}
}
